package org.test.common;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.test.myTree.AbstractTree.EmergencyTree;

public class Context {

	public static ServletContext servletContext;
	public static WebApplicationContext webApplicationContext;


	/**
	 * 得到request对象
	 * 
	 * @return request
	 */
	public static HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	/**
	 * 得到response对象
	 * 
	 * @return request
	 */
	public static HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	/**
	 * 得到Session对象
	 * 
	 * @return Session
	 */
	public static HttpSession getSession() {
		return getRequest().getSession();
	}

	/**
	 * 得到servletContent对象
	 * 
	 * @return
	 */
	public static ServletContext getServletContext() {
		return servletContext;
	}

	/**
	 * 得到spring上下文
	 * 
	 * @return
	 */
	public static WebApplicationContext getWebApplicationContext() {
		// 例子: HibernateDao dao =
		// (HibernateDao)webApplicationContext.getBean("dao");
		return webApplicationContext;
	}

	/**
	 * 从spring配置文件中得到Bean的实例
	 * 
	 * @param beanName
	 *            名称
	 * @return Bean 实例
	 */
	public static Object getSpringBean(String beanName) {
		ServletContext servletContext = getServletContext();
		WebApplicationContext wac = WebApplicationContextUtils
				.getWebApplicationContext(servletContext);
		return wac.getBean(beanName);
	}

	/**
	 * 获取上下文根路径
	 * 
	 * @return
	 */
	public static String getContextPath() {
		return ServletActionContext.getRequest().getContextPath();
	}

	/**
	 * 获取上下文URL全路径
	 * 
	 * @return
	 */
	public static String getContextAllPath() {
		return getRequest().getScheme() + "://" + getRequest().getServerName()
				+ ":" + getRequest().getServerPort()
				+ getRequest().getContextPath();
	}
}
